package com.warf.warftool.was;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;

import com.ibm.ws.scripting.WasxShell;
import com.ibm.wsspi.ssl.RetrieveSignersHelper;
import com.warf.warftool.utils.WarfUtils;

public class WasDeploy  implements Runnable
{
	String dmgrHostName= "localhost";
	String dmgrPortName="8082";
	String dmgrUsername;
	String dmgrPassword;
	String soapCfgURL;
    String sslCfgURL;
    String deployScript;
    private String rootFolder;
    private String scriptPath;
    String parm;
    String warfAppName;
    String serverJVMName;
    String earPath="";
    String earfiles="";
    String warfiles= "";
    String enableLogging="false";
    String autoRestart="false";
    String startTime="";
    String endTime= "";
    boolean sendemail=false;
    boolean enablebackup=false;
    String  emailTo="";
    String emailFrom="WarfTool@No-Reply.com";
    String  smtphost="";
    String filename="";
    String installType="install";
    
    int exitcode=1;
	
	public WasDeploy(String appName, String fname){
		soapCfgURL = "soap.client.props.ibm";
	    sslCfgURL = "ssl.client.props.ibm";
	    rootFolder = "/";
	    filename=fname;
	    scriptPath=rootFolder;	
	    warfAppName=appName;
	    readPropertiesValues();
	}
	
	public WasDeploy(String appName){
		soapCfgURL = "soap.client.props.ibm";
	    sslCfgURL = "ssl.client.props.ibm";
	    rootFolder = "/";
	    scriptPath=rootFolder;	
	    warfAppName=appName;
	}
	
	
	@Override
	public void run() {
		// TODO Auto-generated method stub
		if(serverJVMName != null){
			runScript();
		}else{
			System.err.println("serverJVMName is null");
		}
		
	}
	
	public void runScript(){
		WasxShell shell = new WasxShell();
		RetrieveSignersHelper.getInstance().autoAcceptSignerAndStoreInTrustStore();
		 if(rootFolder != null){
			 soapCfgURL = (new StringBuilder("file:")).append(rootFolder).append("/etc/").append(soapCfgURL).toString();
	         sslCfgURL = (new StringBuilder("file:")).append(rootFolder).append("/etc/").append(sslCfgURL).toString();
	         System.setProperty("was.install.root", rootFolder);
	         System.setProperty("user.root", (new StringBuilder(String.valueOf(rootFolder))).append("/etc/").toString());
	         
		 }
		 System.setProperty("com.ibm.SOAP.ConfigURL", soapCfgURL);
	     System.setProperty("com.ibm.SSL.ConfigURL", sslCfgURL);
	     System.setProperty("SCRIPTPATH", getScriptsPath());
	     System.setProperty("BACKUPDIR", getBackupPath());
	     System.setProperty("WEBAPPSDIR", earPath);
	     System.setProperty("org.apache.soap.util.net.SSLUtils.buildSSLSocket.timeout", "6000000");
	     try
	        {
	    	   List<String> argslist=new ArrayList<String>();
	    	   argslist.add("-connType");
	    	   argslist.add("SOAP");
	    	   argslist.add("-host");
	    	   argslist.add(dmgrHostName);
	    	   argslist.add("-port");
	    	   argslist.add(dmgrPortName);
	    	   argslist.add("-lang");
	    	   argslist.add("jython");
	    	   argslist.add("-user");
	    	   argslist.add(dmgrUsername);
	    	   argslist.add("-password");
	    	   argslist.add(dmgrPassword);
	    	   argslist.add("-f");
	    	   argslist.add(getDeployScript());
	    	   if(enableLogging.equalsIgnoreCase("true")){
	    		   argslist.add("-l");
	    	   }
	    	   
	    	   if(autoRestart.equalsIgnoreCase("true")){
	    		   argslist.add("-r");
	    	   }
	    	   if(enablebackup == true){
	    		   argslist.add("-b");
	    	   }
	    	   System.out.println("Filename: "+filename);
	    	   System.out.println("earfiles: "+earfiles);
	    	   System.out.println("warfiles: "+warfiles);
	    	   if(! filename.equalsIgnoreCase("")){
	    		   if(filename.endsWith(".ear")){
		    		   argslist.add("-e");
		    		   argslist.add(filename);
		    	   }
		    	   
		    	   
		    	   if(filename.endsWith(".war")){
		    		   argslist.add("-w");
		    		   argslist.add(filename);
		    	   }
	    	   }else{
	    		   if(!earfiles.equalsIgnoreCase("")){
	    			   argslist.add("-e");
		    		   argslist.add(earfiles);
	    		   }
	    		   if(!warfiles.equalsIgnoreCase("")){
	    			   argslist.add("-w");
		    		   argslist.add(warfiles);
	    		   }
	    	   }
	    	   
	    	   argslist.add("-a");
	    	   argslist.add(getInstallType());
	    	   
	    	   argslist.add("-n");
    		   argslist.add(warfAppName);
	    	   argslist.add(serverJVMName);  
	           System.out.println((new StringBuilder("*********************")).append(shell.getConnectionType()).toString());
	           String[] ol = argslist.toArray(new String[argslist.size()]);
	           startTime=new Date().toString();
	           System.out.println("*********************************************START TIME: "+startTime);
	           shell.run(ol);
	           exitcode=shell.getReturnCode();
	           endTime=new Date().toString();
	           if(sendemail){
	        	   sendEmail();
	           }
	           System.out.println("**********************************************END TIME: "+endTime+ " Exit code: "+exitcode);
	           
	           
	        }
	        catch(Exception e)
	        {
	            e.printStackTrace();
	        }
	}
	
	public String getDeployScript(){
		String deployscript=WarfUtils.getPropertyBaseRoot(warfAppName,"deploy.script");
		if(deployscript != null){
			System.out.println("Deployment script : "+deployscript);
			return deployscript;
		}else{
			return scriptPath+"/jython/deploy/Deploy.py";
		}
		
	}
	public void sendEmail(){
		System.out.println("Sending Email.....");
		//System.out.println(getEmailString());
		HtmlEmail email = new HtmlEmail();
		if(!smtphost.equalsIgnoreCase("") ){
			if(!emailTo.equalsIgnoreCase("")){
				
				try {
					email.setHostName(smtphost);
					email.addTo(emailTo);
					email.setFrom(emailFrom);
					email.setSubject("Application Deployment: "+warfAppName+ " Instance: "+serverJVMName+ " STATUS: "+getExitCodeAsString());
					email.setHtmlMsg("<html>"+getEmailStringHtml()+"</html>");
					email.setTextMsg("Your email client does not support HTML messages \n"+getEmailString());
					email.send();
					System.out.println("OK");
					
				} catch (EmailException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}else{
				System.err.println("Email To is undefined");
			}
		}else{
			System.err.println("SMPT Host is not defined in configuration properties");
		}
		
	}
	
	public String getEmailStringHtml(){
			return "<body>" +
					"<h1> WARF TOOL: "+warfAppName+"</h1>" +
					"<table width='100%'>" +
					"<tr><td>Warf Application Name:</td><td>"+warfAppName+"</td></tr>" +
					"<tr><td>Server JVM Name:</td><td>" +serverJVMName+"</td></tr>" +
					"<tr><td>Deployment Manager</td><td>"+dmgrHostName+"</td></tr>" +
					"<tr><td>File Name: </td><td>"+filename+"</td></tr>"+
					"<tr><td>Start Time:</td><td>"+startTime+"</td></tr>"+
					"<tr><td>End Time:</td><td>"+endTime+"</td></tr>"+
					"<tr bgcolor='"+getExitCodeColor()+"'><td>Exit Code:</td><td>"+exitcode+"</td></tr>"+
					"</table>" +
					"</body>" +
					"";
	}
	public String getEmailString(){
		return  "WARF TOOL:				\t " +" \n "+
				"WARF Application Name: \t "+warfAppName+ " \n "+
				"Server JVM:            \t "+serverJVMName+" \n "+
				"Deployment Manager:    \t "+dmgrHostName+" \n "+
//				"Ear Files:				\t "+earfiles+" \n "+
//				"War Files:             \t "+warfiles+" \n "+
				"Filename				\t "+filename+" \n "+	
				"Start Time: 			\t "+startTime+" \n "+
				"End Time:              \t "+endTime+" \n "+
				"Return Code:           \t "+getExitCodeAsString();
	}
	
	public String getExitCodeColor(){
		if (exitcode == 0){
			return "#48C44E";
		}else if(exitcode == 1){
			return "#FCF40B";
		}else{
			return "#FC270B";
		}
	}
	public String getExitCodeAsString(){
		if(exitcode == 0){
			return "SUCCESS";
		}else{
			return "FAILED";
		}
	}
	
	
	
	public String getInstallType() {
		return installType;
	}

	public void setInstallType(String installType) {
		this.installType = installType;
	}
	
	

	public String getDmgrHostName() {
		return dmgrHostName;
	}

	public void setDmgrHostName(String dmgrHostName) {
		this.dmgrHostName = dmgrHostName;
	}

	public String getDmgrPortName() {
		return dmgrPortName;
	}

	public void setDmgrPortName(String dmgrPortName) {
		this.dmgrPortName = dmgrPortName;
	}

	public String getDmgrUsername() {
		return dmgrUsername;
	}

	public void setDmgrUsername(String dmgrUsername) {
		this.dmgrUsername = dmgrUsername;
	}

	public String getDmgrPassword() {
		return dmgrPassword;
	}

	public void setDmgrPassword(String password) {
		
		if(password.startsWith("{xor}")){
			this.dmgrPassword=WarfUtils.decryptWasPassword(password);
		}else{
			this.dmgrPassword=password;
		}
	}

	public String getWarfAppName() {
		return warfAppName;
	}

	public void setWarfAppName(String warfAppName) {
		this.warfAppName = warfAppName;
	}

	public String getEarPath() {
		return earPath;
	}

	public void setEarPath(String earPath) {
		this.earPath = earPath;
	}

	public String getEarfiles() {
		return earfiles;
	}

	public void setEarfiles(String earfiles) {
		this.earfiles = earfiles;
	}

	public String getWarfiles() {
		return warfiles;
	}

	public void setWarfiles(String warfiles) {
		this.warfiles = warfiles;
	}

	public String getFilename() {
		return filename;
	}

	public void setFilename(String filename) {
		this.filename = filename;
	}

	public String getScriptsPath(){
		String scriptPath=WarfUtils.getPropertyValue(WarfUtils.PROP_BASE_NAME+".scripts.path");
		if(scriptPath != null){
			return scriptPath;
		}else{
			return "/";
		}
	}
	public String getBackupPath(){
		String scriptPath=WarfUtils.getPropertyBaseRoot(warfAppName,"backup.path");
		if(scriptPath != null){
			File file = new File(scriptPath);
			if(file.isDirectory()){
				System.out.println(warfAppName+ " Backup is not a valid Directory: "+scriptPath);
				try {
					return file.getCanonicalPath();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			enablebackup=false;
			return "/";
			
		}else{
			enablebackup=false;
			return "/";
		}
	}
	

	public void readPropertiesValues(){
		System.out.println(WarfUtils.PROP_BASE_NAME+".wasInstallPath");
		String wasInstall=WarfUtils.getPropertyValue(WarfUtils.PROP_BASE_NAME+".wasInstallPath");
		if(wasInstall != null){
			System.out.println("WAS Install Path: "+wasInstall);
			rootFolder=wasInstall;
		}
		String sPath=WarfUtils.getPropertyValue(WarfUtils.PROP_BASE_NAME+".scripts.path");
		if(sPath != null){
			System.out.println("WAS Script Path: "+sPath);
			scriptPath=sPath;
		}
		String serverName=WarfUtils.getPropertyBaseRoot(warfAppName,"serverName");
		if(serverName != null){
			System.out.println("serverName  : "+serverName);
			serverJVMName=serverName;
		}
		String earStringpath=WarfUtils.getPropertyBaseRoot(warfAppName,"ear.path");
		if(earStringpath != null){
			System.out.println("earStringpath  : "+earStringpath);
			earPath=earStringpath;
		}
		
//		String earfilesString=WarfUtils.getPropertyBaseRoot(warfAppName,"ear.files");
//		if(earfilesString != null){
//			System.out.println("earfiles  : "+earfilesString);
//			
//			earfiles=earfilesString;
//		}
//		
//		String warfilesString=WarfUtils.getPropertyBaseRoot(warfAppName,"war.files");
//		if(warfilesString != null){
//			System.out.println("war files  : "+warfilesString);
//			warfiles=warfilesString;
//		}
		
		String dHost=WarfUtils.getPropertyBaseRoot(warfAppName,"dmgr.hostname");
		if(dHost != null){
			System.out.println("Deployment Manager : "+dHost);
			dmgrHostName=dHost;
		}
		
		
		String dport=WarfUtils.getPropertyBaseRoot(warfAppName,"dmgr.port");
		if(dport != null){
			System.out.println("Deployment Manager port : "+dport);
			dmgrPortName=dport;
		}
		
		String duser=WarfUtils.getPropertyBaseRoot(warfAppName,"dmgr.username");
		if(duser != null){
			System.out.println("Deployment Manager user : "+duser);
			dmgrUsername=duser;
		}
		
		String dpasswordEncryp=WarfUtils.getPropertyBaseRoot(warfAppName,"dmgr.password");
		if(dpasswordEncryp != null){
			if(dpasswordEncryp.startsWith("{xor}")){
				dmgrPassword=WarfUtils.decryptWasPassword(dpasswordEncryp);
			}else{
				dmgrPassword=dpasswordEncryp;
			}
		}
		
		String enableLoggingString=WarfUtils.getPropertyBaseRoot(warfAppName,"enableLogging");
		if(enableLoggingString != null){
			System.out.println("enableLoggingString  : "+enableLoggingString);
			enableLogging=enableLoggingString;
		}
		
		String autoRestartString=WarfUtils.getPropertyBaseRoot(warfAppName,"autoRestart");
		if(autoRestartString != null){
			System.out.println("autoRestartString  : "+autoRestartString);
			autoRestart=autoRestartString;
		}
		
		String emailEnable=WarfUtils.getPropertyBaseRoot(warfAppName,"email.send.enable");
		if(emailEnable != null){
			if(emailEnable.equalsIgnoreCase("true")){
				System.out.println("Send Email Enabled  : "+emailEnable);
				sendemail= true;
			}
			
		}
		
		String emailto=WarfUtils.getPropertyBaseRoot(warfAppName,"email.send.to");
		if(emailto != null){
			
			emailTo=emailto;
		}
		String emailfrom=WarfUtils.getPropertyBaseRoot(warfAppName,"email.send.from");
		if(emailfrom != null){
			
			emailFrom=emailfrom;
		}
		
		String smtp=WarfUtils.getPropertyBaseRoot(warfAppName,"email.smtp.hostname");
		if(smtp != null){
			smtphost=smtp;
		}
		String ebackup=WarfUtils.getPropertyBaseRoot(warfAppName,"backup.enabled");
		if(ebackup != null){
			if(ebackup.equalsIgnoreCase("true")){
				enablebackup=true;
			}
			
		}
	}

	

}
